package org.example;

/**
 * DCL(double check lock双层检查锁)
 *
 * @author zhang
 */
public class Singleton {
    /**
     * sonar，@{link https://blog.csdn.net/m0_37891289/article/details/120265894}
     */
    private static volatile Singleton singleton = null;

    private Singleton() {
    }

    /**
     * 返回一个单例对象
     */
    public static Singleton getInstance() {
        //第一次校验singleton是否为空
        if (singleton == null) {
            synchronized (Singleton.class) {
                //第二次校验singleton是否为空
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }


    public static void main(String[] args) {
        //创建100个线程，获取单例对象
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(Thread.currentThread().getName() + " : " + org.example.Singleton.getInstance().hashCode())
            ).start();
        }
    }
}